var pageSize = 20;
var startIndex = 0;

var searchDs;
var searchKeyWordField;
var main_Panel;

function getSearchForm() {
	searchKeyWordField = new Ext.form.TextField({
		fieldLabel : TXT_search_keyword_label,
		id : 'keyword',
		name : 'keyword',
		allowBlank : true,
		afterRender : function() {
			searchKeyWordField.getEl().on('keyup', function(e) {
				e.stopEvent();
				if ((e.getKey() == Ext.EventObject.ENTER)) {
					searchButtonClick();
				}
			})
		}
	});

	var searchButton = new Ext.Button({
		id : "searchButton",
		text : TXT_search_button_text,
		type : "button",
		cls : 'x-toolbar',
		handler : searchButtonClick
	});

	var searchForm = new Ext.FormPanel({
		frame : true,
		layout : 'column',
		labelAlign : 'right',
		buttonAlign : 'left',
		labelWidth : 60,
		border : false,
		region : 'north',
		height : 60,
		tbar : [
				"-",
				"<span style='font-weight:bold;font-size:11px'>"
						+ TXT_Top_Keyword_Title + "</span>", '->' ],
		style : 'text-align:right;',
		items : [ {
			columnWidth : .99,
			html : "&nbsp;"
		}, {
			layout : 'form',
			width : 200,
			style : 'margin:4px 0 0 0;',
			labelAlign : 'right',
			items : [ searchKeyWordField ]
		}, {
			layout : 'form',
			width : 50,
			style : 'margin:4px 0 0 0;',
			buttonAlign : 'left',
			items : [ searchButton ]
		} ]
	});

	return searchForm;
}

function getSearchGrid() {
	var searchSm = new Ext.grid.RowSelectionModel({
		singleSelect : true
	});
	var searchCm = new Ext.grid.ColumnModel(
			[
					{
						header : '<div style="text-align:center" height="20">'
								+ TXT_Common_Keyword + '</div>',
						dataIndex : 'keyword',
						width : 160,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : '<div style="text-align:center" height="20">'
								+ TXT_Common_Keyword_Spell + '</div>',
						dataIndex : 'spell',
						width : 160,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : '<div style="text-align:center" height="20">'
								+ TXT_Common_Keyword_Number + '</div>',
						dataIndex : 'number',
						width : 160,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : '<div style="text-align:center" height="20">'
								+ TXT_Common_Keyword_Count + '</div>',
						dataIndex : 'count',
						width : 160,
						renderer : function(v) {
							return "<div ext:qtip='" + v + "'>" + v + "</div>";
						}
					},
					{
						header : '<div style="text-align:center" height="20">'
								+ TXT_Common_Operation + '</div>',
						dataIndex : 'keyword',
						width : 160,
						renderer : function(v) {
							return "<div width='100%' style='text-align:center'><a style='color:blue;text-decoration:underline;cursor:pointer' onClick=deleteKeyword('"
									+ v
									+ "')>"
									+ TXT_common_delete
									+ "</a></div>";
						}
					} ]);

	searchDs = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({
			url : DISPATCH_URL
		}),
		reader : new Ext.data.ExJsonReader({
			root : 'results',
			totalProperty : 'totalCount',
			id : 'id',
			fields : [ {
				name : 'keyword'
			}, {
				name : 'spell'
			}, {
				name : 'number'
			}, {
				name : 'count'
			} ]
		})
	});

	searchDs.baseParams = {
		'cmd' : 'topCommand',
		'action' : 'getTopKeyword'
	};

	var searchGrid = new Ext.grid.GridPanel(
			{
				border : false,
				region : 'center',
				ds : searchDs,
				cm : searchCm,
				sm : searchSm,
				stripeRows : true,
				loadMask : {
					msg : 'searching...'
				},
				viewConfig : {
					forceFit : true
				},
				listeners : {
					'keydown' : function(e) {
						e.stopEvent();
						PagingToolbar_KeyEvent(Ext
								.getCmp('searchGridPagingToolbar'), e);
					}
				},
				bbar : new Ext.PagingToolbar(
						{
							id : 'searchGridPagingToolbar',
							pageSize : pageSize,
							height : 18,
							store : searchDs,
							displayInfo : true,
							displayMsg : TXT_common_paging,
							emptyMsg : TXT_common_no,
							onPagingKeydown : function(e) {
								PagingToolbar_KeyEvent(this, e);
							},
							onClick : function(which) {
								switch (which) {
								case 'prev':
									startIndex = startIndex - pageSize;
									break;
								case 'first':
									startIndex = 0;
									break;
								case 'next':
									startIndex = startIndex + pageSize;
									break;
								case 'last':
									startIndex = ((this.store.getTotalCount() / pageSize) | 0)
											* pageSize;
									break;
								default:
								}

								// Gets data
								loadData();
							}
						})
			});

	loadData();

	return searchGrid;
}

function PagingToolbar_KeyEvent(thisPagingToolbar, e) {
	if ((e.getKey() == Ext.EventObject.ENTER)) {
		var currPage = thisPagingToolbar.readPage();
		var totalPage = thisPagingToolbar.getPageData().pages;

		if (currPage > totalPage) {
			Ext.Msg.alert(TXT_common_hint, TXT_Common_Correct_PageNum);
			return;
		} else {
			if (currPage <= 0) {
				startIndex = 0;
			} else {
				startIndex = (currPage - 1) * pageSize;
			}

			// Gets data
			loadData();
		}
	}
	return;
}

function displaySearchPanel() {

	var searchForm = getSearchForm();
	var searchGrid = getSearchGrid();
	main_Panel = new Ext.Panel({
		border : false,
		region : 'center',
		layout : 'border',
		margins : '5 5 5 5',
		cmargins : '5 5 5 5',
		items : [ searchForm, searchGrid ]
	});

	// loadData();

	BestvSearch.glb_mainPanel.add(main_Panel);
	BestvSearch.drawMainFrame(TXT_app_name + ' - ' + TXT_search_title, null);
}

Ext.onReady(displaySearchPanel);

function searchButtonClick() {
	startIndex = 0;

	// Gets data
	loadData();
}

function loadData() {
	var keyWord = '';
	if (searchKeyWordField && searchKeyWordField.getValue()) {
		keyWord = searchKeyWordField.getValue().trim();
		if (TXT_Common_Keyword_Search_emptyMsg == keyWord) {
			keyWord = '';
		}
	}

	searchDs
			.load({
				params : {
					keyword : keyWord,
					start : startIndex,
					limit : pageSize,
					dataSourceKey : BestvSearch.DataSourceKey
				},
				callback : function(r, options, success) {
					if (r.length == 0 && !success) {
						if (searchDs.reader.responseText == '[null]') {
							Ext.Msg
									.alert(
											TXT_common_hint,
											TXT_common_relogin,
											function() {
												window.location.href = '../eni/common/logout.jsp';
											});
							return;
						} else {
							Ext.Msg.alert(TXT_common_hint,
									TXT_SITE_CONFIGURATION_CHECK);
							return;
						}
					}
				}
			});
}

function deleteKeyword(keyword) {

	var confirmTitle = TXT_Common_Delete_confirm;
	var confirmMsg = TXT_Keyword_Delete_confirm_msg + TXT_Common_Keyword + ":"
			+ keyword;
	var successMsg = TXT_common_delete_success;
	var url = DISPATCH_URL + "?cmd=topCommand&action=deleteTopKeyword&keyword="
			+ keyword + '&flag=' + Math.random();
	confirmHandle(confirmTitle, confirmMsg, url, successMsg);
}

function confirmHandle(confirmTitle, confirmMsg, url, successMsg) {
	Ext.Msg.confirm(confirmTitle, confirmMsg, function(btn) {
		if (btn == 'yes') {
			var conn = Ext.lib.Ajax.getConnectionObject().conn;
			conn.open("GET", url, false);
			conn.send(null);
			if (conn.responseText == 'success') {
				Ext.Msg.alert(TXT_common_hint, successMsg);
				loadData();
			} else {
				Ext.Msg.alert(TXT_common_hint, TXT_common_access_fail);
			}
		}
	});
}
